package com.example.bnuzzu.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.bnuzzu.common.dto.*;
import com.example.bnuzzu.common.lang.Result;
import com.example.bnuzzu.entity.*;
import com.example.bnuzzu.mapper.HouseinfoMapper;
import com.example.bnuzzu.mapper.UserinfoMapper;
import com.example.bnuzzu.service.*;
import com.example.bnuzzu.util.ShiroUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Select;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author BNUZZU
 * @since 2021-04-13
 */

@Slf4j
@RestController
public class HouseinfoController {
    final static String LOCAL_PATH = "File/images/upload";
    final static String URL = "http://localhost:8081/File/images/upload/";
    @Autowired
    HouseinfoService houseinfoService;
    @Autowired
    HousedetailsService housedetailsService;
    @Autowired
    HouseimageService houseimageService;
    @Autowired
    UserinfoMapper userinfoMapper;
    @Autowired
    OrderinfoService orderinfoService;
    @Autowired
    FavoritehouseService favoritehouseService;

    /**
     * 首页房屋查找界面
     * @param p 页面
     * @return Result
     */
    @GetMapping("/showhouses/{page}")
    public Result list(@PathVariable(name = "page") Integer p){
       //分页查询 最近更新的未被租出的房屋
        Page<HouseListDto> page = new Page<>(p, 6);
        IPage<HouseListDto> pageData = houseinfoService.selectHousePage(page,0);
        Map<String,Object> map = new LinkedHashMap<>();
        map.put("pageData",pageData);
        return Result.success(map);
    }

    @PostMapping("/searchhouses")
    public Result search(@RequestBody SearchDto searchDto){
        //分页查询 符合条件的表
        if (searchDto.getRegion() != null) {
            searchDto.setRegion(searchDto.getRegion().replace("undefined", "").replace("全部", ""));
        }
        Page<HouseListDto> page = new Page<>(searchDto.getPage(), 6);
        IPage<HouseListDto> pageData = houseinfoService.searchHousePage(page,searchDto,0);
        Map<String,Object> map = new LinkedHashMap<>();
        map.put("pageData",pageData);
        return Result.success(map);
    }

    @PostMapping("/gethouses")
    public Result get(@RequestBody SearchDto searchDto){
        //分页查询 符合条件的表
        Page<HouseListDto> page = new Page<>(searchDto.getPage(), 6);
        IPage<HouseListDto> pageData = houseinfoService.searchHousePage(page,searchDto,0);
        Map<String,Object> map = new LinkedHashMap<>();
        map.put("pageData",pageData);
        return Result.success(map);
    }

    /**
     * 房屋详情界面
     * @param id 房屋id
     * @return Result
     */
    @GetMapping("/gethouse/{id}")
    public Result info(@PathVariable(name = "id") Integer id){
        Houseinfo houseinfo = houseinfoService.getById(id);
        Houseimage houseimage = houseimageService.getById(id);
        Housedetails housedetails = housedetailsService.getById(id);
        Map<String,Object> map = new LinkedHashMap<>();
        int userid = 0;
        int friends = 1;
        Assert.notNull(houseinfo,"该房屋已被删除");

        HouseDto houseDto = new HouseDto();
        BeanUtil.copyProperties(houseinfo,houseDto);
        BeanUtil.copyProperties(housedetails,houseDto);

        if(ShiroUtil.getProfile() != null){
            userid = ShiroUtil.getProfile().getUserid().intValue();
        }

        QueryWrapper<Favoritehouse> wrapper = new QueryWrapper<>();
        wrapper.eq("userid",userid)
                .eq("houseid",id);
        int i = favoritehouseService.count(wrapper);



        if(ShiroUtil.getProfile() != null){
            QueryWrapper<Orderinfo> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("houseid",id)
                    .eq("orderstatus",1)
                    .eq("tenantid",ShiroUtil.getProfile().getUserid().intValue());
            friends += orderinfoService.count(wrapper1);
            wrapper1.clear();
            wrapper1.eq("houseid",id)
                    .eq("orderstatus",1)
                    .eq("ownerid",ShiroUtil.getProfile().getUserid().intValue());
            friends += orderinfoService.count(wrapper1);
            if(friends > 1){
                List<UserListDto> friendsList = userinfoMapper.findFriends(id);
                map.put("friendsList",friendsList);
                friends = friendsList.size();
            }
        }

        String username = userinfoMapper.selectById(houseinfo.getUserid()).getUsername();
        String phone = userinfoMapper.selectById(houseinfo.getUserid()).getPhone();

        houseDto.setUsername(username);
        houseDto.setPhone(phone);
        houseDto.setFriends(String.valueOf(friends));
        houseDto.splitFa();

        map.put("housedto",houseDto);
        map.put("images",houseimage);
        map.put("isCollected",i>0);
        map.put("isRented", friends > 1);
        return Result.success(map);
    }

    @RequiresAuthentication
    @PostMapping("/deleteHouse")
    public Result delHouse(@RequestBody Houseinfo houseinfo){
        if(houseinfo.getUserid() != null){
            Assert.isTrue(houseinfo.getUserid() == ShiroUtil.getProfile().getUserid().intValue(), "没有权限编辑");
        }else {
            return Result.fail(500,"请重新登录",null);
        }

        houseinfoService.removeById(houseinfo);

        return Result.success(null);
    }

    @RequiresAuthentication
    @PostMapping("/uploadimages")
    public Result editimages(@RequestParam("file") MultipartFile[] images,HttpServletResponse response){
        //图片存储
        String[] imagesName = new String[images.length];
        String[] url = new String[images.length];
        Random r = new Random();
        try{
            for(int i = 0;i<images.length;i++)
            {
                imagesName[i] = DateTime.now().toString("yyyyMMddhhmmss")+r.nextInt(101)+images[i].getOriginalFilename();
                url[i] = URL+imagesName[i];
            }

            for(int i=0;i<images.length;i++) {
                InputStream inputStream = images[i].getInputStream();
                Path directory = Paths.get(LOCAL_PATH);
                if (!Files.exists(directory)) {
                    Files.createDirectories(directory);
                }
                long copy = Files.copy(inputStream, directory.resolve(imagesName[i]));
            }
        }catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.fail(502, "上传失败", null);
        }
        Map<String,String[]> map = new LinkedHashMap<>();
        map.put("images",imagesName);
        map.put("url",url);
        return  Result.success(map);
    }

    /**
     * 房屋添加/更新页面
     * @param houseDto 房屋数据
     * @return Result 结果
     */
    @RequiresAuthentication
    @PostMapping("/edithouse")
    public Result editInfo(@RequestBody HouseDto houseDto, HttpServletResponse response){
        //判断是否修改自己名下的房屋
        if(userinfoMapper.selectById(ShiroUtil.getProfile().getUserid()).getUsertype() != 1){
            if(houseDto.getUserid() != null){
                Assert.isTrue(Integer.parseInt(houseDto.getUserid()) == ShiroUtil.getProfile().getUserid().intValue(), "没有权限编辑");
            }else {
                return Result.fail(500,"请重新登录",null);
            }
        }

        houseDto.fillFa();

        //房屋信息
        Houseinfo houseinfo = new Houseinfo();
        BeanUtil.copyProperties(houseDto,houseinfo);

        //房屋详情
        Housedetails housedetails = new Housedetails();
        BeanUtil.copyProperties(houseDto,housedetails);

        //房屋图片
        Houseimage houseimage = new Houseimage();
        String[] images = houseDto.getImages();
        for(int i=0;i<images.length;i++){
            switch (i){
                case 1 -> houseimage.setImage1(images[i]);
                case 2 -> houseimage.setImage2(images[i]);
                case 3 -> houseimage.setImage3(images[i]);
                case 4 -> houseimage.setImage4(images[i]);
                default -> houseimage.setMainimage(images[i]);
            }
        }

        //新建
        if(houseinfo.getHouseid() == null){
            if(images.length == 0){
                return Result.fail(502,"请上传至少一张图片",null);
            }
            houseinfoService.saveOrUpdate(houseinfo);

            housedetails.setHouseid(houseinfo.getHouseid());
            housedetailsService.saveOrUpdate(housedetails);
            houseimage.setHouseid(houseinfo.getHouseid());
            houseimageService.saveOrUpdate(houseimage);
        }
        //更新
        else{
            houseinfoService.saveOrUpdate(houseinfo);
            housedetailsService.saveOrUpdate(housedetails);
            if(images.length >0){
                LambdaUpdateWrapper<Houseimage> wrapper = new LambdaUpdateWrapper<>();
                wrapper.eq(Houseimage::getHouseid,houseinfo.getHouseid());
                wrapper.set(Houseimage::getMainimage,houseimage.getMainimage());
                if(houseimage.getImage1() == null){
                    wrapper.set(Houseimage::getImage1,null);
                }else{
                    wrapper.set(Houseimage::getImage1,houseimage.getImage1());
                }
                if(houseimage.getImage2() == null){
                    wrapper.set(Houseimage::getImage2,null);
                }else{
                    wrapper.set(Houseimage::getImage2,houseimage.getImage2());
                }
                if(houseimage.getImage3() == null){
                    wrapper.set(Houseimage::getImage3,null);
                }else{
                    wrapper.set(Houseimage::getImage3,houseimage.getImage3());
                }
                if(houseimage.getImage4() == null){
                    wrapper.set(Houseimage::getImage4,null);
                }else{
                    wrapper.set(Houseimage::getImage4,houseimage.getImage4());
                }
                houseimageService.update(wrapper);
            }
        }

        return  Result.success(null);
    }


}

